package org.beetl.core.om;

import org.beetl.core.exception.BeetlException;
import org.beetl.core.fun.MethodInvoker;
import org.beetl.core.fun.ObjectUtil;

import java.lang.reflect.Method;

/**
 *
 * Java Record Support
 * @author xiandafu
 * @see "DefaultAAFactory" && "AsmAAFactory"
 */

public class RecordBeanAA extends AttributeAccess {

    public static final RecordBeanAA INSTANCE = new RecordBeanAA();
    protected RecordBeanAA() {

    }

    @Override
    public Object value(Object o, Object name) {
        Class c = o.getClass();
        String key = (String) name;
		Method m = null;
		try {
			try{
				m =  c.getMethod(key);
			}catch (NoSuchMethodException methodException){
				//POJO or General Get，also support！
			}

			if(m==null){
				return  pojoValue(c,o,key);
			}
			return m.invoke(o);

		} catch (Exception e) {
			throw new BeetlException(BeetlException.ATTRIBUTE_NOT_FOUND, " Record  Class " + c.getName() + " no field " + key, e);
		}


    }

	protected   Object pojoValue(Class c, Object o,String key){
		//普通类
		MethodInvoker mi = ObjectUtil.getInvokder(c, key);
		if(mi!=null){
			return mi.get(o);
		}else{
			throw new BeetlException(ObjectUtil.hasPrivateAttribute(c, key)
					? BeetlException.ATTRIBUTE_NOT_FOUND_PRIVATE : BeetlException.ATTRIBUTE_NOT_FOUND, key);
		}
	}
}
